<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="../assets/logo.png" alt="">
      </div>

      <el-form class="login-form" ref="loginForm" :model="loginForm" label-width="100px" :rules="loginRules">
        <el-form-item label="用户名:" prop="username">
          <el-input prefix-icon="iconfont icon-user" type="text" placeholder="账号" v-model="loginForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码:" prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" type="password" placeholder="密码" v-model="loginForm.password" prop="password"></el-input>
        </el-form-item>

        <el-form-item class="submit-form">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>

import request from '../network/request'

export default {
  name: 'MyLogin',
  data() {
    return {
      // 表单绑定的对象
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 定义表单中的规则
      loginRules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: '请输入正确的用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入正确的密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单内容
    resetForm() {
      this.$refs.loginForm.resetFields()
    },
    // 登录
    login() {
      // 验证登录
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await request.post('login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功')
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  position: relative;
  height: 100%;
  background-color: #2b4b6b;
}
.login-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 450px;
  height: 300px;
  border-radius: 3px;
  background-color: #fff;
}
.login-header {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 140px;
  height: 140px;
  background-color: #eee;
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid #ccc;
  box-shadow: 0 0 10px #ddd;
  img {
    width: 100%;
    height: 100%;
  }
}
.login-form {
  margin-top: 120px;
  padding-right: 20px;
}
.submit-form {
  text-align: center;
}
</style>
